package org.yxing.palpalgps.activity;

import java.io.IOException;
import java.util.Iterator;

import org.apache.http.NoHttpResponseException;
import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.AbstractActivity;
import org.yxing.palpalgps.R;
import org.yxing.palpalgps.adapter.ChatGroupAdapter;
import org.yxing.palpalgps.models.ChatGroup;
import org.yxing.palpalgps.oauth.OAuth;
import org.yxing.palpalgps.provider.RecentChatsProvider.RecentChats;
import org.yxing.palpalgps.utils.Utils;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

/**
 * chat group list
 * @author yuxing
 *
 */
public class GroupChatsActivity extends AbstractActivity implements OnItemClickListener{
    private static final String TAG = GroupChatsActivity.class.getSimpleName();
    
    private static final int RESULT_ADD = 1;
    private static final String URL_GROUP_CHAT_INFO = "groupchat/info";
    private static final String URL_GROUP_CHAT_ALL = "groupchat/allgroups";
    
    private ChatGroupAdapter mAdapter;
    private ListView mListView;
    
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.group_chats);
        setTitle(getString(R.string.chat_group));
        
        mListView = (ListView) findViewById(android.R.id.list);
        
        mAdapter = new ChatGroupAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        
        new MyAsyncTask().execute();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, 3, 0, getString(R.string.add)).setIcon(
                android.R.drawable.ic_menu_add);
        menu.add(0, 4, 0, getString(R.string.refresh)).setIcon(android.R.drawable.ic_menu_rotate);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
        case 3:
            startActivityForResult(new Intent(this, CreateGroupChatActivity.class), RESULT_ADD);
            break;
        case 4:
            new MyAsyncTask().execute();
            break;
        }
        return true;
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v(TAG, "a");
        if (resultCode == RESULT_OK) {
            Log.v(TAG, "b");
            if (requestCode == RESULT_ADD) {
                new MyAsyncTask().execute();
            }
        }
    }
    
    private class MyAsyncTask extends AsyncTask<Void, Void, String> {
        
        protected void onPreExecute() {
            showPd();
        }

        @Override
        protected String doInBackground(Void... params) {
            String result = null;
            try {
                result = Utils.openUrl(URL_GROUP_CHAT_ALL, OAuth.createAuthParams());
            } catch (NoHttpResponseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }
        
        protected void onPostExecute(String response) {
            if (response != null) {
                try {
                    mAdapter.clear();
                    JSONObject json = new JSONObject(response);
                    JSONObject result = json.getJSONObject("result");
                    Iterator<String> iterator = result.keys();
                    while (iterator.hasNext()) {
                        JSONObject obj = result.getJSONObject(iterator.next());
                        ChatGroup cg = new ChatGroup();
                        cg.setGid(obj.getString("gid"));
                        cg.setName(obj.getString("name"));
                        cg.setAdmin(obj.getInt("admin") == 1);
                        mAdapter.add(cg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                cancelPd();
            }
        }
        
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ChatGroup cg = mAdapter.getItem(position);
        
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra("fuid", cg.getGid());
        intent.putExtra("name", cg.getName());
        intent.putExtra("type", RecentChats.TYPT_GROUP);
        
        startActivity(intent);
    }
}
